package pl.edu.pw.perg.compinfodb.datamodel;

import java.util.HashMap;
import java.util.Map;

import pl.edu.pw.perg.compinfodb.entities.PhysicalElement;
import pl.edu.pw.perg.compinfodb.entities.attribute.IAttribute;
import pl.edu.pw.perg.compinfodb.entities.attribute.ListAttribute;
import pl.edu.pw.perg.compinfodb.entities.attribute.NumericAttribute;
import pl.edu.pw.perg.compinfodb.entities.attribute.TextAttribute;
import pl.edu.pw.perg.compinfodb.entities.field.Field;

public class TableData {

	public static final String SLOT = "SLOT";
	public static final String LOCATION = "LOCATION";
	public static final String LABEL = "LABEL";
	public static final String ELEMENT_TYPE = "ELEMENT_TYPE";

	private Map<String, Object> values = new HashMap<String, Object>();
	private PhysicalElement pe;

	public Object getValue(String key) {

		Object td = values.get(key);
		Object value = null;
		if (td instanceof TextAttribute)
			value = ((TextAttribute) td).getTextValue();
		else if (td instanceof NumericAttribute)
			value = ((NumericAttribute) td).getNumericValue();
		else if (td instanceof ListAttribute)
			value = ((ListAttribute) td).getSelectedListFieldItem().getValue();
		else
			value = td;
		return value;

	}

	public void setValue(String key, Object value) {
		values.put(key, value);
	}

	public boolean matchesFilter(Map<String, String> filter) {
		if(filter == null)
			return true;
		for (String key : filter.keySet()) {
			if(getValue(key) == null)
				continue;
			String value = getValue(key).toString();
			if (!value.contains(filter.get(key))) {
				return false;
			}
		}
		return true;
	}

	public TableData(PhysicalElement pe) {
		this.pe = pe;
		values.put(ELEMENT_TYPE, pe.getElementType());
		values.put(LABEL, pe.getLabel());
		 values.put(LOCATION, pe.getVirtualElement().toString());
		 values.put(SLOT, (pe.getVirtualElement().getLocation()!=-1)?
		 pe.getVirtualElement().getLocation() : "N/A");
		Map<Field, IAttribute> attributes = pe.getAttributesMap();
		for (Field field : attributes.keySet()) {
			values.put(field.getFieldName(), attributes.get(field));
		}

	}

	public static String[] getConstHeaders() {
		String[] ret = { LABEL, ELEMENT_TYPE, LOCATION, SLOT };
		return ret;
	}

	public PhysicalElement getPe() {
		return pe;
	}

}
